home *** CD-ROM | disk | FTP | other *** search
- Path: news.lpr.carel.fi!usenet
- From: Ari Lukumies <aril@cmt.lpr.mail.carel.fi>
- Newsgroups: comp.lang.c++
- Subject: Re: Did I Miss Something?
- Date: Thu, 04 Apr 1996 12:54:47 +0200
- Organization: Carelcomp Products
- Message-ID: <3163AA77.5901@cmt.lpr.mail.carel.fi>
- References: <N.040396.105136.51@ix.netcom.com>
- NNTP-Posting-Host: renoir.cclahti.carel.fi
- Mime-Version: 1.0
- Content-Type: text/plain; charset=us-ascii
- Content-Transfer-Encoding: 7bit
- X-Mailer: Mozilla 2.0 (WinNT; I)
-
- Jerry Hewett wrote:
- > [snip]
- >
- > // OBJSTRNG.CPP, from Chapter 6 - More Encapsulation.
- >
- > class box {
- > int length;
- > int width;
- > char *line_of_text;
- > public:
- > box(char *input_line);
- > void set(int new_length, int new_width);
- > int get_area(void);
- > };
- >
- > /*
- > Just guessing, but here goes...
- >
- > Below is the constructor for "box". The object doesn't exist until the
- > constructor creates it. Since a pointer to a "known" fixed-length string
- > is being passed to the constructor, the compiler determines the amount of
- > memory required to store the string "small box ", allocates space for it
- > in the object, and copies it into this space.
- >
- > Once the object passes out of scope this "magically" created chunk of
- > memory allocation disappears along with the object... (???)
-
- Not quite - compiler does not determine and allocate anything. main() calls the
- constructor with the parameter "small box". This is a constant character string (read:
- array ending with a '\0') that is stored somewhere in the memory. The assignment
- line_of_text = input_line simply assigns the address of this string to line_of_text,
- without allocating any memory. Similarly, there's no destructor, so the memory is not
- freed, and of course should not be, because it was not allocated by the ctor in the
- first place.
-
- > */
- >
- > box::box(char *input_line)
- > {
- > length = 8;
- > width = 8;
- > line_of_text = input_line;
- > }
-
- To make the ctor allocate some memory, one would use something like
-
- box::box(char *input_line)
- {
- // line_length just added for clarity
- line_length = strlen(input_line) + 1;
- line_of_text = new char[line_length];
- strcpy(line_of_text, input_line);
- }
-
- and provide a destructor
-
- box::~box()
- {
- line_length = 0;
- delete [] line_of_text;
- line_of_text = 0;
- }
-
- The zeroings here are to provide that you won't use the members after destruction (or
- if you try to, you'll probably have a core dump or a GPF). Of course, in this example,
- line_length and destructor would have been added to the class declaration also.
-
- >
- > main()
- > {
- > box small("small box ");
- >
- > }
- >
-
- Later,
- AriL
- --
- All my opinions are mine and mine alone.
-